package com.fancy.learncenter.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.adapter.ReleasePIcAdapter;
import com.fancy.learncenter.adapter.ReleaseWDPIcAdapter;
import com.fancy.learncenter.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.adapter.base.CustomViewHold;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.YgtDetailDesDataBean;
import com.fancy.learncenter.common.StatusBarCompat;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.PermissionUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.CustomProgressDialog;
import com.fancy.learncenter.view.PopupWindowCutPic;
import com.fancy.learncenter.view.RatingBarView;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class YGTAddActivity extends TakePhotoActivity {
    private static final int ACCESS_LOCATION_RESULT_CODE = 100111;
    String classifyId;
    String startNum = "0";
    @Bind(R.id.goodsRecycleView)
    RecyclerView goodsRecycleView;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.custom_ratingbar)
    RatingBarView customRatingbar;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.feature)
    EditText feature;
    @Bind(R.id.confrim_time)
    EditText confrimTime;
    @Bind(R.id.extra_num)
    EditText extraNum;
    @Bind(R.id.rating_num)
    TextView ratingNum;
    @Bind(R.id.description)
    EditText description;
    @Bind(R.id.pro_name)
    EditText proName;
    @Bind(R.id.right_tv)
    TextView rightTv;
    @Bind(R.id.select_num)
    EditText selectNum;

    YgtDetailDesDataBean ygtDetailDesDataBean;
//    @Bind(R.id.online_recycleView)
//    RecyclerView onlineRecycleView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ygtadd);
        ButterKnife.bind(this);

        StatusBarCompat.compat(this, getResources().getColor(R.color.toolbar_color));

        ygtDetailDesDataBean = (YgtDetailDesDataBean) getIntent().getParcelableExtra("ygtDetailDesDataBean");

        classifyId = getIntent().getStringExtra("classifyId");

        takePhoto = getTakePhoto();

        takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);


        title.setText("添加项目");
        rightTv.setText("提交");
        rightTv.setVisibility(View.VISIBLE);
        initRecycleView();

        initPicRecycle();

//        initOnlieRecycleView();
        customRatingbar.setOnRatingListener(new RatingBarView.OnRatingListener() {
            @Override
            public void onRating(Object bindObject, int RatingScore) {
                startNum = RatingScore + "";
                ratingNum.setText(RatingScore + "星");
            }
        });

        initData();
    }


    CommonRecycleViewAdapter goodsAdapter;

    ArrayList<YgtDetailDesDataBean.OptionsBean> goodDatas;

    private void initPicRecycle() {
        goodDatas = new ArrayList<>();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        goodsRecycleView.setLayoutManager(linearLayoutManager);

        goodsAdapter = new CommonRecycleViewAdapter<YgtDetailDesDataBean.OptionsBean>(this, R.layout.activity_ygt_goods_item, goodDatas) {
            @Override
            public void bindView(final CustomViewHold customViewHold, final YgtDetailDesDataBean.OptionsBean item, final int position) {
                EditText goodsEt = customViewHold.getView(R.id.goodsEt);
                goodsEt.setText(item.getGoods_option());
                goodsEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        item.setGoods_option(s.toString());
                    }
                });
                EditText priceEt = customViewHold.getView(R.id.priceEt);
                priceEt.setText(item.getMoney());
                priceEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        item.setMoney(s.toString());
                    }
                });


                ImageView delete = customViewHold.getView(R.id.delete);

                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goodDatas.remove(position);
//                        editTexts.remove(customViewHold.getLayoutPosition());
//                        priceEts.remove(customViewHold.getLayoutPosition());

                        goodsAdapter.notifyDataSetChanged();
                    }
                });


            }
        };

        goodsRecycleView.setAdapter(goodsAdapter);
    }

    ArrayList<String> picData = new ArrayList<>();

    ReleasePIcAdapter releaseWDPIcAdapter;
    PopupWindowCutPic popupWindowCutPic;

    private void initRecycleView() {

        releaseWDPIcAdapter = new ReleasePIcAdapter(this, new ArrayList<String>(), false);
        releaseWDPIcAdapter.setCallBack(new ReleasePIcAdapter.CallBack() {
            @Override
            public void OnClick() {
                if (popupWindowCutPic == null) {
                    popupWindowCutPic = new PopupWindowCutPic(recycleView);
                    popupWindowCutPic.setOnClickListener(new PopupWindowCutPic.CutPicCallBack() {
                        @Override
                        public void choose() {
//                            takePhoto.onPickFromGallery();
                            takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);
                            takePhoto.onPickMultiple(6);
                        }

                        @Override
                        public void cancel() {

                        }

                        @Override
                        public void camera() {
                            takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);
                            takePhoto.onPickFromCaptureWithCrop(Utils.getCutPicPath(), Utils.getCutPicCropOptions());
                        }

                        @Override
                        public void see() {

                        }
                    });

                }

                popupWindowCutPic.isShow();

            }
        });

        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 3);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);

        recycleView.setAdapter(releaseWDPIcAdapter);
    }

//    ReleaseWDPIcAdapter onlineAdapter;

//    private void initOnlieRecycleView() {
//        ArrayList itemData = new ArrayList();
//
//        onlineAdapter = new ReleaseWDPIcAdapter(this, itemData);
//
//        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 3);
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        onlineRecycleView.setLayoutManager(linearLayoutManager);
//
//        onlineRecycleView.setAdapter(onlineAdapter);
//    }

    TakePhoto takePhoto;


    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                    //权限被允许（如果被拒绝的话就会提示去设置中打开权限）
                    startActivityForResult(new Intent(YGTAddActivity.this, MapLocationActivity.class), ACCESS_LOCATION_RESULT_CODE);
                    break;
            }
        }
    };

    /**
     * 定位权限授权回调
     */
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }


    private CropOptions getCropOptions() {

        CropOptions.Builder builder = new CropOptions.Builder();
//        builder.setWithOwnCrop(false);
        return builder.create();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        if (result.getImages() != null && !TextUtils.isEmpty(result.getImage().getCompressPath())) {

            ArrayList<TImage> images = result.getImages();


            for (int i = 0; i < images.size(); i++) {
//                picData.add(images.get(i).getCompressPath());

                releaseWDPIcAdapter.itemDatas.add(releaseWDPIcAdapter.itemDatas.size() - 1, "file://" + images.get(i).getCompressPath());

            }
        }

//        ArrayList<String> itemDatas = new ArrayList();
//        itemDatas.addAll(picData);
//        itemDatas.add("res://com.superservice.lya/" + R.mipmap.ic_tianjia);

        releaseWDPIcAdapter.notifyDataSetChanged();


//        if (result.getImage() != null && !TextUtils.isEmpty(result.getImage().getCompressPath())) {
//            releaseWDPIcAdapter.itemDatas.add(releaseWDPIcAdapter.itemDatas.size() - 1, "file://" + result.getImage().getCompressPath());
//
//        }
//
//        releaseWDPIcAdapter.notifyDataSetChanged();
    }


    Dialog dialog;
    boolean isSubmit = false;

    private void disDia() {

        isSubmit = false;
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    private void submit() {


        if (isSubmit) {
            return;
        } else {
            isSubmit = true;
            if (dialog == null) {
                dialog = CustomProgressDialog.creatRequestDialog(this);
            }
            dialog.show();

        }

        Map maps = new HashMap();

        List<String> datas = new ArrayList();

        for (int i = 0; i < releaseWDPIcAdapter.itemDatas.size() - 1; i++) {
            if (releaseWDPIcAdapter.itemDatas.get(i).contains("file://")) {
                String filePath = releaseWDPIcAdapter.itemDatas.get(i);
                datas.add("data:image/jpeg;base64," + Utils.imageToBase64(filePath.replaceAll("file://", "")));
            }

        }

        ArrayList<String> price = new ArrayList<>();

        ArrayList<String> priceOption = new ArrayList<>();

        for (int i = 0; i < goodDatas.size(); i++) {
            price.add(goodDatas.get(i).getMoney());
            priceOption.add(goodDatas.get(i).getGoods_option());
        }

        maps.put("classifyId", classifyId);
        maps.put("feature", feature.getText().toString());
        maps.put("period", confrimTime.getText().toString());
        maps.put("subsidy", extraNum.getText().toString());
        maps.put("star", startNum);
        maps.put("description", description.getText().toString());
        maps.put("goodsName", proName.getText().toString());
        maps.put("peopleNum", selectNum.getText().toString());

        if (ygtDetailDesDataBean != null) {
            maps.put("goodsId", ygtDetailDesDataBean.getId());
        }

        List<String> removeImg = new ArrayList();

        if (onlieImg != null) {

            for (int j = 0; j < onlieImg.size(); j++) {

                for (int i = 0; i < releaseWDPIcAdapter.itemDatas.size(); i++) {

                    if (onlieImg.get(j).getCase_img().equals(releaseWDPIcAdapter.itemDatas.get(i))) {

                        break;
                    } else if (i == releaseWDPIcAdapter.itemDatas.size() - 1) {

                        removeImg.add(onlieImg.get(j).getId());

                    }
                }


            }

        }
        HttpMehtod.getInstance().releaseYgt(maps, price, priceOption, datas, removeImg, new IdeaObserver<BaseDataBean>() {

            @Override
            public void onSuccess(BaseDataBean stringBaseDataBean) {
                disDia();
                ToastUtil.show("发布成功");
                finish();


            }

            @Override
            public void onFail(int errorCode) {
                disDia();
            }

        });

    }

    private void initData() {
        if (ygtDetailDesDataBean != null) {
            feature.setText(ygtDetailDesDataBean.getFeature());

            confrimTime.setText(ygtDetailDesDataBean.getPeriod());

            extraNum.setText(ygtDetailDesDataBean.getSubsidy());

            proName.setText(ygtDetailDesDataBean.getName());


            startNum = ygtDetailDesDataBean.getStar();

            customRatingbar.setClickable(true);

            customRatingbar.setStar(Integer.parseInt(startNum), true);

            description.setText(ygtDetailDesDataBean.getDescription_notag());


            goodsAdapter.notifyDataSetChanged((ArrayList) ygtDetailDesDataBean.getOptions());

            selectNum.setText(ygtDetailDesDataBean.getPeople_num());

            ratingNum.setText(startNum + "星");

            if (ygtDetailDesDataBean.getCaseX() != null && ygtDetailDesDataBean.getCaseX().size() > 0) {
                onlieImg = ygtDetailDesDataBean.getCaseX();
                ArrayList<String> picDatas = new ArrayList<>();
                for (int i = 0; i < ygtDetailDesDataBean.getCaseX().size(); i++) {
                    picDatas.add(ygtDetailDesDataBean.getCaseX().get(i).getCase_img());
                }
                picDatas.add("res://com.superservice.lya/" + R.mipmap.ic_tianjia);
                releaseWDPIcAdapter.notifyDataSetChanged(picDatas);
            } else {
                ArrayList itemData = new ArrayList();
                itemData.add("res://com.superservice.lya/" + R.mipmap.ic_tianjia);

                releaseWDPIcAdapter.notifyDataSetChanged(itemData);
            }
        } else {
            ArrayList itemData = new ArrayList();
            itemData.add("res://com.superservice.lya/" + R.mipmap.ic_tianjia);

            releaseWDPIcAdapter.notifyDataSetChanged(itemData);
        }


    }

    List<YgtDetailDesDataBean.CaseBean> onlieImg;

    @OnClick({R.id.back, R.id.right_tv, R.id.add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_tv:
                submit();
                break;
            case R.id.add:

                YgtDetailDesDataBean.OptionsBean optionsBean = new YgtDetailDesDataBean.OptionsBean();
                optionsBean.setGoods_option("");
                optionsBean.setMoney("");
                goodDatas.add(optionsBean);

                goodsAdapter.notifyItemInserted(goodDatas.size());
                break;
        }
    }
}
